import { createPersistStore, BaseState } from './index'
import { Project, CreateProjectParams } from '@/types/project'
import { nanoid } from 'nanoid'

interface ProjectState extends BaseState {
  projects: Project[];
  currentProject: Project | null;
  
  // 操作函数
  fetchProjects: () => Promise<Project[]>;
  createProject: (params: CreateProjectParams) => Promise<Project>;
  updateProject: (id: string, updates: Partial<Project>) => Promise<void>;
  deleteProject: (id: string) => Promise<void>;
  selectProject: (id: string) => void;
}

// 初始状态
const initialState = {
  projects: [],
  currentProject: null,
  isLoading: false,
  error: null
}

export const useProjectStore = createPersistStore<ProjectState>(
  'projects',
  initialState as any,
  (set, get) => ({
    ...initialState,
    
    fetchProjects: async () => {
      set({ isLoading: true, error: null });
      
      try {
        // 在实际实现中，这里会从API或本地存储获取数据
        // 现在我们先使用存储在Zustand中的数据
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 300));
        const { projects } = get();
        set({ isLoading: false });
        return projects;
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    createProject: async (params) => {
      set({ isLoading: true, error: null });
      
      try {
        // 创建新项目
        const now = new Date().toISOString();
        const newProject: Project = {
          id: nanoid(),
          ...params,
          status: 'draft',
          wordCount: 0,
          tags: params.tags || [],
          createdAt: now,
          updatedAt: now
        };
        
        // 更新状态
        set(state => ({ 
          projects: [...state.projects, newProject],
          currentProject: newProject,
          isLoading: false 
        }));
        
        return newProject;
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    updateProject: async (id, updates) => {
      set({ isLoading: true, error: null });
      
      try {
        // 更新项目
        set(state => {
          const projects = state.projects.map(p => 
            p.id === id 
              ? { ...p, ...updates, updatedAt: new Date().toISOString() } 
              : p
          );
          
          // 如果当前选中的项目被更新，也更新currentProject
          const currentProject = state.currentProject?.id === id
            ? { ...state.currentProject, ...updates, updatedAt: new Date().toISOString() }
            : state.currentProject;
            
          return { projects, currentProject, isLoading: false };
        });
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    deleteProject: async (id) => {
      set({ isLoading: true, error: null });
      
      try {
        // 删除项目
        set(state => {
          const projects = state.projects.filter(p => p.id !== id);
          
          // 如果删除的是当前选中的项目，重置currentProject
          const currentProject = state.currentProject?.id === id
            ? null
            : state.currentProject;
            
          return { projects, currentProject, isLoading: false };
        });
      } catch (error) {
        set({ error: String(error), isLoading: false });
        throw error;
      }
    },
    
    selectProject: (id) => {
      const { projects } = get();
      const project = projects.find(p => p.id === id) || null;
      set({ currentProject: project });
    }
  })
); 